/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.role;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.model.core.ContentDocument;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.RoleManager;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.webapp.acegi.UserManagerDaoImpl;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.RoleForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Deletes role
 * </p>
 * <p><a href="DeleteRoleAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.20 $ $Date: 2008/04/29 17:48:09 $
 * @struts.action path="/core/role/delete"
 * name="roleForm"
 * scope="request"
 * validate="false"
 * roles="core-role-delete"
 * @struts.action-forward name="listRoles"
 * path="/core/role/list.do"
 * redirect="true"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/role/list.do"
 */
public final class DeleteRoleAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		RoleForm roleForm = (RoleForm) form;
		String roleName = null;
		if ( !GenericValidator.isBlankOrNull(roleForm.getName()) ) {
			roleName = roleForm.getName();
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing role name. Returning to list...");
			}
			return mapping.findForward("listRoles");
		}

		RoleManager roleManager = (RoleManager) getBean(Constants.ROLE_MANAGER_BEAN);
		Role role = roleManager.retrieveRole(roleName);

		if ( role == null ) {
			// role not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("roleNotFound", new ActionMessage("core.role.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listRoles");
		}

		if ( role.getFixed().booleanValue() ) {
			ActionMessages errors = new ActionMessages();
			errors.add("roleIsFixed", new ActionMessage("core.role.errors.isFixed"));
			saveErrors(request, errors);
			return mapping.findForward("listRoles");
		}

        List resources = new ArrayList(role.getResources());
        List pages = new ArrayList(role.getPages());

        UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
        PartialCollection users = userManager.listUsers(null);
        UserManagerDaoImpl userManagerDaoImpl = (UserManagerDaoImpl) getBean(Constants.USER_DETAILS_SERVICE_BEAN);

		roleManager.deleteRole(roleName);

        for (Iterator i = users.iterator(); i.hasNext();) {
            User user = (User) i.next();
            if (user.getName().equals(request.getRemoteUser())) {
                userManagerDaoImpl.updateUser(user);
            }
        }

        CacheUtil cacheUtil = CacheUtil.getInstance(request);
        SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());

        for (int i = 0; i < resources.size(); i++) {
            ContentResource resource = (ContentResource) resources.get(i);
            cacheUtil.updateResourceRolesInCache(resource.getUri(), WebappUtil.rolesToString(resource.getRoles()));
            if (resource instanceof ContentDocument) {
                ContentDocument document = (ContentDocument) resource;
                searchManager.reIndexDocument(document, request);
            }
        }

        for (int i = 0; i < pages.size(); i++) {
            Page page = (Page) pages.get(i);
            searchManager.reIndexPage(page, request);
/*
            if (page instanceof ContentPage) {
                ContentPage contentPage = (ContentPage)page;
                cacheUtil.updateContentPageRolesInCache(contentPage.getUri(), WebappUtil.rolesToString(contentPage.getRoles()));
            }
*/
        }

        // flush CP cache to avoid a situation when user permissions for
        // CP menu items are changed but he/she still obtains cached version
        // of page
        cacheUtil.flushContentPageCache();

		return mapping.findForward("listRoles");
	}
}
